import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class PhotoThread extends Thread {

    Image image=null;    
    String fileName=null;
    PhotoThreadInvoker invoker=null;
    int width;
    int height;
    
    /** Creates a new instance of PlayerThread */
    public PhotoThread(PhotoThreadInvoker invoker, String filename, int width, int height) {
        this.invoker=invoker;
        this.fileName=filename;
        this.width=width;
        this.height=height;
    }
    
    // The run method creates a player and starts the playback of the audiofile
    public void run(){
        try{
        	FileConnection fc = (FileConnection) Connector.open(fileName);		
			InputStream fis = fc.openInputStream ();
			int length = (int) fc.fileSize();
			
			byte[] b =  new byte[length];
			fis.read(b);			

			fis.close() ;
			fc.close();
			
			image = scaleImage(Image.createImage ( b , 0 , length ));
			invoker.photoStarted();
        }catch(Exception e){
        	System.out.println(e.toString());
        	invoker.photoError(e.toString());
        }
    }
    
    // close the player and end the playback
    public void close()
    {
        try{
        	image = null;
            //System.out.println("playeThread.close");
            
        }catch(Exception e){System.out.println(e.toString());}
    }
    
    
    public Image scaleImage(Image image) {
		int sourceWidth = image.getWidth();
		int sourceHeight = image.getHeight();
		
		double factor;		
		double thumbWidth = width;// 64;
		double thumbHeight = height;

		double divW = sourceWidth / thumbWidth;
		double divH = sourceHeight / thumbHeight;				
		
		if (divW > divH){
			factor = divW;
		}else{
			factor = divH;
		}
		
		int smallWidth = (int) ((double) sourceWidth / factor);
		int smallHeight = (int) ((double) sourceHeight / factor);

		Image small = Image.createImage(smallWidth, smallHeight);
		Graphics g = small.getGraphics();

		for (int y = 0; y < smallHeight; y++) {
			for (int x = 0; x < smallWidth; x++) {
				g.setClip(x, y, 1, 1);
				int dx = x * sourceWidth / smallWidth;
				int dy = y * sourceHeight / smallHeight;
				g.drawImage(image, x - dx, y - dy, Graphics.LEFT | Graphics.TOP);
			}
		}
		Image scaledDownImage = Image.createImage(small);
		return scaledDownImage;
	}
}
